<template>
  <div class="order-page">
    <div class="section">
      <div class="address-selector">
        <el-select
            v-model="selectedAddressId"
            placeholder="请选择地址"
            class="select-address"
            @change="handleAddressChange"
        >
          <el-option
              v-for="address in addressList"
              :key="address.id"
              :label="address.name + ' ' + address.address"
              :value="address.id"
          ></el-option>
        </el-select>
      </div>

      <div class="delivery-time-selector">
        <el-select
            v-model="selectedDeliveryTime"
            placeholder="请选择送达时间"
            class="select-delivery-time"
        >
          <el-option
              :key="0"
              :label="`立即送出（${new Date(new Date().getTime() + 60 * 60 * 1000).toLocaleString()}）`"
              :value="0"
          ></el-option>
          <el-option
              v-for="(i, index) in availableDeliveryTimes"
              :key="index"
              :label="`${new Date(new Date().getTime() + 60 * 60 * 1000 + i * 20 * 60 * 1000).toLocaleString()} `"
              :value="index + 1"
          ></el-option>
        </el-select>
      </div>
    </div>

    <div class="section">
      <div class="table-container">
        <el-table :data="blogInfo" stripe border style="width: 100%">
          <el-table-column prop="dname" label="菜品" />
          <el-table-column prop="price" label="价格" />
          <el-table-column prop="totalprice" label="总价格" />
          <el-table-column prop="count" label="数量" />
        </el-table>
      </div>

      <div class="total-price">
        <p>总价为 {{ totalPrice }} 元</p>
      </div>

      <div class="payment-button">
        <el-button type="primary" @click="handlePayment">支付</el-button>
      </div>
    </div>
  </div>
</template>

<script setup>
import { computed, onMounted, ref } from 'vue';
import request from '@/utils/canteen';
import { ElMessage, ElSelect, ElOption, ElButton, ElTable, ElTableColumn } from 'element-plus';
import { useRouter } from 'vue-router'; // 确保导入了useRouter

const router = useRouter(); // 使用useRouter钩子函数创建router实例

const blogInfo = ref([]);
const loginUser = JSON.parse(sessionStorage.getItem('loginUser'));
const stuId = ref(loginUser? loginUser.id : null);
const selectedAddressId = ref(null);
const addressList = ref([]);

// 新增：送达时间相关
const selectedDeliveryTime = ref(0);  // 默认值为立即送出（一小时后）
const availableDeliveryTimes = ref([1, 2, 3, 4, 5, 6]);  // 表示可选的时间，即一小时后的每隔 20 分钟

const fetchAddressList = () => {
  request({
    url: '/address/getAll',
    method: 'get',
    params: { stuid: stuId.value },
  }).then((response) => {
    if (response.data.errorCode === 200) {
      addressList.value = response.data.data;
      if (addressList.value && addressList.value.length > 0) {
        console.log('所有地址及其状态:', addressList.value);
        let selectedAddress = addressList.value.find(address => address.status === "1");
        selectedAddressId.value = selectedAddress? selectedAddress.id : null;
      } else {
        selectedAddressId.value = null;
      }
    } else {
      ElMessage.error('获取地址列表失败');
    }
  }).catch((error) => {
    console.error('请求地址列表时发生错误:', error);
    ElMessage.error('请求地址列表时发生错误');
  });
};

const getDish = () => {
  request({
    url: '/cart/getAll',
    method: 'get',
  }).then((response) => {
    console.log(response);
    if (response.status === 200) {
      blogInfo.value = response.data;
    } else {
      ElMessage.error('请求失败');
    }
  }).catch((error) => {
    console.error("请求失败:", error);
    ElMessage.error('请求失败');
  });
};

const totalPrice = computed(() => {
  return blogInfo.value.reduce((total, item) => total + item.totalprice , 0);
});

const handleAddressChange = (newAddressId) => {
  const selectedAddress = addressList.value.find(address => address.id === newAddressId);
  sessionStorage.setItem('selectedAddress', JSON.stringify(selectedAddress));
  console.log('选中的地址ID:', newAddressId);
};

const handlePayment = async () => {
  // 从 sessionStorage 中获取数据
  const loginUser = JSON.parse(sessionStorage.getItem('loginUser'));
  const selectedDish = JSON.parse(sessionStorage.getItem('selectedDish'));

  // 处理地址选择
  let selectedAddress;
  if (selectedAddressId.value) {
    selectedAddress = addressList.value.find(address => address.id === selectedAddressId.value);
  } else {
    selectedAddress = addressList.value.find(address => address.status === "1");
  }

  if (!loginUser ||!selectedDish ||!selectedAddress) {
    ElMessage.error('必要的信息不完整，请刷新页面重试');
    return;
  }

  try {
    const indent = {
      useid: loginUser.id,
      mallid: selectedDish.mid,
      addressid: selectedAddress.id,
      name:selectedAddress.name,
      address:selectedAddress.address,
      phone:selectedAddress.phone,
      mname:selectedDish.mname,
      totalprice: totalPrice.value
    };

    // 新增：添加送达时间到 indent 对象
    const currentTime = new Date();
    const oneHourLater = new Date(currentTime.getTime() + 60 * 60 * 1000);
    const selectedTimeStr = selectedDeliveryTime.value === 1
        ? new Date().toISOString().split('T')[0] +' '+ new Date().toLocaleString('zh-CN', { hour12: false, timeZone: 'Asia/Shanghai' }).split(' ')[1].split('.')[0]
        : new Date(oneHourLater.getTime() + selectedDeliveryTime.value * 20 * 60 * 1000).toISOString().split('T')[0] +' '+ new Date(oneHourLater.getTime() + selectedDeliveryTime.value * 20 * 60 * 1000).toLocaleString('zh-CN', { hour12: false, timeZone: 'Asia/Shanghai' }).split(' ')[1].split('.')[0];
    indent.gettime = selectedTimeStr;

    // 发送请求到后端 API 添加订单
    console.log('Request data:', indent);
    const indentResponse = await request({
      url: '/indent/add',
      method: 'post',
      data: indent
    });

    if (indentResponse.status!== 200) {
      ElMessage.error('添加订单失败');
      return;
    }

    const indentId = indentResponse.data;
    sessionStorage.setItem('lastOrderId', indentId);

    // 执行 importFromCart 接口
    const lastOrderId = JSON.parse(sessionStorage.getItem('lastOrderId'));
    const importResponse = await request({
      url: '/indentdetail/importFromCart',
      method: 'post',
      params: { indentdetailid: lastOrderId }
    });

    if (importResponse.status!== 200) {
      ElMessage.error('执行 importFromCart 接口失败');
      return;
    }
    clearCart()
    router.push({ path: `/home/canteen/order` });
    ElMessage.success('订单创建成功，请到我的订单去支付');
  } catch (error) {
    console.error("请求失败:", error);
    ElMessage.error('请求失败');
  }
};

const clearCart = () => {
  request({
    url: '/cart/clear',
    method: 'post',
  }).then((response) => {
    if (response.status === 200) {
      blogInfo.value = []; // 清空购物车数据
    } else {
      ElMessage.error('清空失败');
    }
  }).catch((error) => {
    console.error("清空购物车请求失败:", error);
    ElMessage.error('清空购物车失败');
  });
};

onMounted(() => {
  fetchAddressList();
  getDish();
});
</script>

<style>
.order-page {
  max-width: 800px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f7f7f7;
  border: 1px solid #ddd;
  border-radius: 8px;
}

.section {
  margin-bottom: 20px;
}

.select-address, .select-delivery-time {
  width: 100%;
}

.table-container {
  margin-bottom: 20px;
}

.total-price {
  text-align: right;
  margin-bottom: 20px;
}

.payment-button {
  text-align: center;
}
</style>
